package com.os.opencv.java.chapter8;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class MatchTemplate2 {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/wanlifuwangshi.jpg");
        HighGui.imshow("wanlifuwangshi", src);
        HighGui.waitKey(0);

        //读取模板图像并在屏幕上显示
        Mat template = Imgcodecs.imread("/Users/matt/Pictures/xi.jpg");
        HighGui.imshow("template", template);
        HighGui.waitKey(0);

        //进行模板匹配，匹配值范围为-1 ~ 1
        Mat result = new Mat();
        Imgproc.matchTemplate(src, template, result, Imgproc.TM_CCOEFF_NORMED);
        System.out.println(result);

        //参数准备
        float[] p = new float[3];
        Scalar red = new Scalar(0,0,255);
        int temprow = template.rows();
        int tempcol = template.cols();

        //搜索匹配值>0.8的像素
        for(int i=0; i< result.rows(); i++){
            for(int j=0; j<result.cols(); j++){
                //获取像素的匹配值
                result.get(i, j, p);
                //匹配值>0.8的像素用矩形画出
                if(p[0] > 0.8){
                    Imgproc.rectangle(src, new Point(j, i), new Point(j + tempcol, i+temprow), red, 3);
                }
            }
        }
        //在屏幕上显示匹配结果
        HighGui.imshow("match", src);
        HighGui.waitKey(0);

        System.exit(0);
    }
}
